const tile = new ol.layer.Tile({
    source: new ol.source.XYZ({
        url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8'
    })
})
const zoom = 4, center = ol.proj.fromLonLat([107.11040599933166, 34.26271532332011])
var map = new ol.Map({
    target: 'map',
    layers: [
        tile
    ],
    view: new ol.View({
        center,
        zoom
    })
});



addLegend()

function addLegend() {
    const legendData = [
        {level: 'red', label: '红色预警', color: 'red'},
        {level: 'orange', label: '橙色预警', color: 'orange'},
        {level: 'yellow', label: '黄色预警', color: 'yellow'},
        {level: 'blue', label: '蓝色预警', color: 'blue'}
    ]
    const canvas = document.getElementById('legends')
    canvas.width = 80
    canvas.height = 88
    const ctx = canvas.getContext('2d')
    const gradient = ctx.createLinearGradient(0,0,0,canvas.height);
    const step =  1 / legendData.length
    legendData.forEach((data, index) => {
        const x = 30
        const y = index * 22 + 11
        ctx.fillStyle = '#000'
        ctx.textAlign = 'left'
        ctx.textBaseline = 'middle'
        ctx.font='12px Arial'
        ctx.fillText(data.label, x, y)
        gradient.addColorStop(step * index, data.color);
    })
    ctx.beginPath()
    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, 22, canvas.height)

    // legendData.forEach((data, index) => {
    //     ctx.beginPath()
    //     const x  = 6
    //     const y = index * 22
    //     ctx.restore()
    //     ctx.fillStyle = data.color
    //     ctx.fillRect(x, y, 14, 14)
    //     ctx.fillStyle = '#000'
    //     ctx.textAlign = 'left'
    //     ctx.textBaseline = 'middle'
    //     ctx.font='12px Arial'
    //     ctx.fillText(data.label, x + 18, y + 8)
    //     ctx.save()
    // })

    // const dom = document.getElementById('legends')
    // legendData.forEach(data => {
    //     const li = document.createElement('li')
    //     li.innerHTML = `
    //         <span class="color" style="background-color: ${data.color}"></span>
    //         ${data.label}
    //     `
    //     dom.appendChild(li)
    // })
}